#coding:utf-8
from models.account.account_user_model import User
from datetime import datetime
from libs.common.send_mail.send_email_libs import send_qq_html_email
from random import choice
from string import printable
from uuid import uuid4
from libs.account.account_auth_libs import logout
import json
def edit_profile(self,name,password):
    if password=='':
        return {'status':False,'msg':'密码不能为空'}
    if name=='':
        return {'status':False,'msg':'姓名不能为空'}
    user=self.current_user
    pre_name=user.name
    user.name=name
    user.password=password
    user.updatetime=datetime.now()
    self.db.add(user)
    self.db.commit()
    if pre_name !=name:
        logout(self)
        return self.redirect('/auth/user_login')
    return {'status':True,'msg':'修改成功'}

def send_email_libs(self,email):
    email_code=''.join([choice(printable[:62]) for i in xrange(6)])
    u=str(uuid4())
    text_dict={
        u:self.current_user.id,
        'email_code':email_code
    }
    redis_text=json.dumps(text_dict)
    content='''
           <p>验证并激活邮箱</p>
           <p><a href="http://39.108.172.126:9003/account/auth_email_code?code={0}&email={1}&user_id={2}">邮箱绑定链接</a></p>
    '''.format(email_code,email,u)
    send_fail=send_qq_html_email('260760495@qq.com',[email],'绑定你的OA邮箱',content)
    if send_fail:
        return {'status':False,'msg':'邮件发送失败'}
    print email,redis_text
    self.conn.setex('email:%s'%email,redis_text,500)
    return {'status':True,'msg':'邮件发成功'}

def auth_email_libs(self,email,email_code,u):
    redis_text=self.conn.get('email:%s'%email)
    if redis_text:
        text_dict=json.loads(redis_text)
        if text_dict and text_dict['email_code']==email_code:
            user=self.current_user
            if not user:
                user=User.by_id(text_dict[u])
            print user
            user.email=email
            user.update_time=datetime.now()
            self.db.add(user)
            self.db.commit()
            return {'status':True,'msg':'邮箱修改成功'}
        return {'status':False,'msg':'验证码错误'}
    return {'status':False,'msg':'验证码过期'}